<!--
* @description 巡检统计
* @author zywu
* @date 2021/03/12 16:32:03
!-->
<template>
  <div class="inspect-statistic">
    <div class="page-body--padding">
      <!-- 切换我的/团队 -->
      <div v-show="active!=2" class="primary-panel is-shadow">
        <div class="d-flex jc-center">
          <div class="yt-capsule d-flex ai-center" :class="['active'+capsule]">
            <div
              class="yt-capsule__item d-flex ai-center jc-center"
              :class="{ 'is-active':capsule==1 }"
              @click="handleCapsuleChange(1)"
            >团队</div>
            <div
              class="yt-capsule__item d-flex ai-center jc-center"
              :class="{ 'is-active':capsule==2 }"
              @click="handleCapsuleChange(2)"
            >我的</div>
          </div>
        </div>
        <div v-show="active==0" class="inspect-statistic__calendar">
          <van-calendar
            v-if="showCalendar"
            ref="calendar"
            :default-date="defaultDate"
            :show-title="false"
            :poppable="false"
            :show-confirm="false"
            :show-mark="false"
            :min-date="minDate"
            :max-date="maxDate"
            :formatter="formatter"
            @select="onSelectDay"
          />
          <van-icon class="arrow arrow-left" name="arrow-left" @click="switchCalendar(-1)" />
          <van-icon class="arrow arrow-right" name="arrow" @click="switchCalendar(1)" />
        </div>

        <div v-show="active==1" class="d-flex ai-center jc-between count-filter">
          <pop-action
            text="标签"
            :options="labelList"
            show-selected
            align="start"
            @change="onCountLabelChange"
            style="width:100px;"
          ></pop-action>
          <pop-date-picker text="日期" align="end" @change="onDateChange"></pop-date-picker>
        </div>
      </div>

      <!-- 清单 -->
      <div v-show="active==0" class="inspect-statistic__filter d-flex ai-center jc-between">
        <pop-action
          ref="popListLabel"
          text="标签"
          :options="labelList"
          align="start"
          @change="onListLabelChange"
          :style="{width:capsule==1?'70px':'100px'}"
        ></pop-action>
        <unit-picker
          ref="popUnit"
          v-show="capsule==1&&userInfo.isMuilUnitUser"
          text="单位"
          @change="onUnitChange"
          style="width:70px;"
        ></unit-picker>
        <pop-action
          ref="popCompleteness"
          text="完成度"
          :options="inspectCompleteness"
          show-selected
          @change="v=>{onPickerChange('result',v)}"
          style="width:70px;"
        ></pop-action>
        <pop-button
          v-show="capsule==1"
          :is-active="!!selectedUser"
          :is-open="showUserSelect"
          :text="selectedUser?selectedUser.name:'责任人'"
          align="end"
          @click.native="handleOpenUserSelect"
          style="width:70px;"
        ></pop-button>
      </div>
      <template v-if="active==0">
        <van-list
          v-model="loading"
          :finished="finished"
          :finished-text="taskList.length>0?'暂无更多':''"
          @load="getTaskList(false)"
        >
          <div class="inspectList_cell" v-for="(item) in taskList" :key="item.id">
            <inspect-module :data-obj="item" :showBtn="false" stamp readonly></inspect-module>
          </div>
        </van-list>
        <div v-if="taskList.length==0" class="no-data-img">
          <img src="../../assets/img/common/defaultnone.png" />
        </div>
      </template>

      <!-- 统计 -->
      <sta-complete v-if="active==1" :is-personal="capsule==2" :data-obj="countData" @jumpTab="jumpTab"></sta-complete>
      <!-- 团队 -->
      <sta-unit-rank
        v-if="active==1&&capsule==1&&userInfo.isMuilUnitUser&&unitRankData.length>0"
        :data-list="unitRankData"
        show-head
        show-more
        :on-click="goUnitRank"
      ></sta-unit-rank>
      <!-- 我的 -->
      <sta-uncomplete v-if="active==1&&capsule==2" :params="myTaskParam"></sta-uncomplete>

      <!-- 不合格点位 -->
      <keep-alive>
        <unqualified-point
          v-if="active==2"
          :labelList="labelList"
          :useProps="useNotOkProps"
          :defaultLabelId="notOkLabelId"
          :month="notOkMonth"
          :defaultUser="notOkUser"
          @onInit="useNotOkProps=false"
        ></unqualified-point>
      </keep-alive>
    </div>

    <van-popup v-model="showUserSelect" round position="bottom" :style="{ height:'80%' }">
      <pop-user-select ref="popUserSelect" @change="onSelectUser"></pop-user-select>
    </van-popup>

    <div v-if="capsule==1&&active==1&&userData.length>0" class="d-flex ai-center man-list">
      <sta-man-card v-for="item in userData" :key="item.account" :data-obj="item" @click.native="goPersonalRank(item)"></sta-man-card>
    </div>

    <van-tabbar v-model="active">
      <van-tabbar-item>
        <span>清单</span>
        <template #icon="props">
          <i class="iconfont" :class="props.active?'icon-qingdanmian':'icon-qingdan-01'"></i>
        </template>
      </van-tabbar-item>
      <van-tabbar-item>
        统计
        <template #icon="props">
          <i class="iconfont" :class="props.active?'icon-tongjimian':'icon-tongji-xian'"></i>
        </template>
      </van-tabbar-item>
      <van-tabbar-item>
        不合格点位
        <template #icon="props">
          <i class="iconfont" :class="props.active?'icon-buhege-mian':'icon-buhegedianwei-xian'"></i>
        </template>
      </van-tabbar-item>
    </van-tabbar>
  </div>
</template>

<script>
import PopPicker from '@/components/PopPicker'
import PopAction from '@/components/PopAction'
import UnitPicker from '@/components/UnitPicker'
import PopDatePicker from '@/components/PopDatePicker'
import StaComplete from './StaComplete.vue'
import StaUncomplete from './StaUncomplete.vue'
import StaUnitRank from './StaUnitRank.vue'
import StaManCard from './StaManCard.vue'
import InspectModule from './InspectModule.vue'
import UnqualifiedPoint from './UnqualifiedPoint'
import { inspectCompleteness } from '@/config/dict'
import PopUserSelect from '../../components/PopUserSelect.vue'
import PopButton from '../../components/PopButton.vue'
import { mapState, mapGetters } from 'vuex'
import {
  getExamineTaskListCount,
  getExamineTaskOrgOrder,
  getExamineTaskPeopleCount,
  getExamineTaskDailyStats,
  getExamineTaskStats,
  getExamineTaskListByPage,
} from '@/api/inspect'
import { getLableList } from '@/api/common'
const today = new Date()
let theYear = today.getFullYear()
let theMonth = today.getMonth()
let theDay = today.getDate()
let year = theYear
let month = theMonth
let day = theDay
let completedDays = []
let uncompletedDays = []
export default {
  name:'InspectStatistic',
  components: {
    PopPicker,
    PopAction,
    UnitPicker,
    StaComplete,
    StaUncomplete,
    StaUnitRank,
    StaManCard,
    InspectModule,
    UnqualifiedPoint,
    PopUserSelect,
    PopButton,
    PopDatePicker,
  },
  props: {
    defaultTab: {
      type: Number,
      default: 0,
    },
    defaultCapsule: {
      type: Number,
      default: 1,
    },
  },
  computed: {
    ...mapState(['userInfo']),
    ...mapGetters(['userFullOrgIds']),
    myTaskParam() {
      return {
        account: this.userInfo.accountName,
        orgIds: this.userFullOrgIds,
        result: 1,
        labelId: this.labelId_count || '',
        beginTime: this.startTime,
        endTime: this.endTime,
        timeType: 2,
        pageSize: 10,
      }
    },
  },
  data() {
    return {
      taskList: [],
      labelList: [],
      countData: {},
      unitRankData: [],
      userData: [],
      showUserSelect: false,
      selectedUser: '',
      inspectCompleteness,
      capsule: 1,
      showCalendar: true,
      defaultDate: null,
      minDate: new Date(year, month, 1),
      maxDate: this.$moment(new Date(year, month + 1, 1))
        .subtract(1, 'days')
        .toDate(),
      active: 0,
      labelId_count: '',
      startTime: '',
      endTime: '',
      labelId_list: '',
      pageIndex: 0,
      loading: false,
      finished: false,
      // 不合格点位默认查询条件
      notOkLabelId: '',
      notOkMonth: '',
      notOkUser: {},
      useNotOkProps: false,
    }
  },
  watch: {
    active(val) {
      if (val == 1) {
        this.getCountData()
      } else if (val == 2) {
      }
      this.$nextTick(() => {
        document.documentElement.scrollTo(0, 0)
      })
    },
    capsule(val) {
      if (this.active == 0) {
        this.getTaskList()
        this.getExamineTaskDailyStats()
      } else if (this.active == 1) {
        this.getCountData()
      }
    },
  },
  created() {
    this.active = this.defaultTab
    this.capsule = this.defaultCapsule
    this.setTime(new Date())
    this.getLableList()
    this.getTaskList()
    this.getExamineTaskDailyStats()
  },

  mounted() {},

  activated() {
    if (this.$route.params.from == 'PersonalRank') {
      this.jumpTab(this.$route.params)
    }
  },

  methods: {
    jumpTab(data) {
      if (data.tabIndex == 0) {
        let targetLabelId = `${this.labelId_count}`
        let targetStartTime = this.startTime
        let targetEndTime = this.endTime
        if (data.from == 'PersonalRank') {
          targetLabelId = `${data.labelId}`
          targetStartTime = data.startTime
          targetEndTime = data.endTime
          this.selectedUser = {
            accountName: data.account,
            name: data.name,
          }
          this.account = data.account
        } else {
          this.selectedUser =
            this.capsule == 1
              ? ''
              : {
                  accountName: this.userInfo.accountName,
                  name: this.userInfo.name,
                }
          this.account = this.capsule == 1 ? '' : this.userInfo.accountName
        }
        this.orgIds = ''
        this.result = data.completeness
        this.labelId_list = targetLabelId
        this.minDate = new Date(targetStartTime)
        this.maxDate = new Date(targetEndTime)
        this.selectedDay = null
        year = this.minDate.getFullYear()
        month = this.minDate.getMonth()
        this.active = 0
        if (data.from != 'PersonalRank' || this.capsule == 1) {
          this.getTaskList()
          this.getExamineTaskDailyStats()
        } else {
          this.capsule = 1
        }
        this.$nextTick(() => {
          this.$refs.popListLabel.setSelected(targetLabelId)
          this.$refs.popCompleteness.setSelected(data.completeness)
          if (data.account && this.$refs.popUserSelect) {
            this.$refs.popUserSelect.setSelected(this.selectedUser)
          }
          if (data.from != 'PersonalRank' && this.$refs.popUserSelect) {
            this.$refs.popUserSelect.setSelected(this.selectedUser || {})
          }
          this.$refs.popUnit.currentOrg = {}
        })
      } else if (data.tabIndex == 2) {
        let targetLabelId = `${this.labelId_count}`
        let targetStartTime = this.startTime
        let targetUser =
          this.capsule == 1
            ? {}
            : {
                name: this.userInfo.name,
                accountName: this.userInfo.accountName,
              }
        if (data.from == 'PersonalRank') {
          targetLabelId = `${data.labelId}`
          targetStartTime = data.startTime
          targetUser = {
            name: data.name,
            accountName: data.account,
          }
        }
        this.notOkLabelId = targetLabelId || ''
        this.notOkMonth = targetStartTime.substr(0, 7)
        this.notOkUser = targetUser
        this.useNotOkProps = true
        this.active = 2
      }
    },
    onSelectDay(date) {
      if (
        this.selectedDay &&
        this.$moment(this.selectedDay).format('yyyy-MM-DD') ==
          this.$moment(date).format('yyyy-MM-DD')
      ) {
        this.defaultDate = null
        this.$refs.calendar.reset()
        this.selectedDay = null
        return this.getTaskList()
      }
      this.selectedDay = date
      this.getTaskList()
    },
    getExamineTaskDailyStats() {
      completedDays = []
      uncompletedDays = []
      getExamineTaskDailyStats({
        account: this.userInfo.accountName,
        orgIds: this.capsule == 1 ? this.userFullOrgIds : '',
        beginTime: this.$moment(this.minDate).format('yyyy-MM') + '-01 00:00',
        endTime:
          this.$moment(this.maxDate).endOf('month').format('YYYY-MM-DD') +
          ' 23:59',
      }).then((res) => {
        for (var k in res.data) {
          let obj = res.data[k]
          if (obj.totalCount) {
            if (obj.finishedCount == obj.totalCount) {
              completedDays.push(k)
            } else {
              uncompletedDays.push(k)
            }
          }
        }
        this.showCalendar = false
        this.defaultDate = this.selectedDay || null
        this.$nextTick(() => {
          this.showCalendar = true
        })
      })
    },
    getExamineTaskStats() {
      getExamineTaskStats({
        account: this.userInfo.accountName,
        orgIds: this.capsule == 1 ? this.userFullOrgIds : '',
        labelId: this.labelId_count,
        beginTime: this.startTime,
        endTime: this.endTime,
      }).then((res) => {
        this.countData = res.data
      })
    },
    getTaskList(isRefresh = true) {
      if (isRefresh) {
        this.pageIndex = 0
        this.taskList = []
        this.finished = false
      }
      this.loading = true
      let beginTime = ''
      let endTime = ''
      if (this.selectedDay) {
        beginTime =
          this.$moment(this.selectedDay).format('yyyy-MM-DD') + ' 00:00'
        endTime = this.$moment(this.selectedDay).format('yyyy-MM-DD') + ' 23:59'
      } else {
        beginTime = this.$moment(this.minDate).format('yyyy-MM') + '-01 00:00'
        endTime =
          this.$moment(this.maxDate).endOf('month').format('YYYY-MM-DD') +
          ' 23:59'
      }
      getExamineTaskListByPage({
        account: this.capsule == 1 ? this.account : this.userInfo.accountName,
        orgIds:
          this.orgIds && this.capsule == 1 ? this.orgIds : this.userFullOrgIds,
        result: this.result || '',
        labelId: this.labelId_list || '',
        beginTime,
        endTime,
        timeType: 2,
        pageIndex: this.pageIndex,
        pageSize: 10,
      }).then((res) => {
        this.taskList = this.taskList.concat(res.data)
        // 加载状态结束
        this.loading = false
        // 数据全部加载完成
        if (this.taskList.length >= res.total) {
          this.finished = true
        } else {
          this.pageIndex++
        }
      })
    },
    getLableList() {
      getLableList({ type: 1 }).then((res) => {
        this.labelList = res.data.map((n) => {
          n.value = n.id
          return n
        })
      })
    },
    setTime(dateObj) {
      let dateStr = this.$moment(dateObj).format('yyyy-MM')
      this.startTime = `${dateStr}-01 00:00`
      this.endTime =
        this.$moment(
          this.$moment(new Date(year, dateObj.getMonth() + 1, 1))
            .subtract(1, 'days')
            .toDate()
        ).format('yyyy-MM-DD') + ' 23:59'
    },
    onUnitChange(obj) {
      this.orgIds = obj.organizationId
      this.getTaskList()
    },
    onDateChange(val) {
      this.setTime(val)
      this.getCountData()
    },
    onCountLabelChange(v) {
      if (v.value == this.labelId_count) return
      this.labelId_count = v.value
      this.getCountData()
    },
    // 统计数据
    getCountData() {
      this.getExamineTaskStats()
      if (this.capsule == 1) {
        this.getExamineTaskOrgOrder()
        this.getExamineTaskPeopleCount()
      }
    },
    // 任务数统计
    getExamineTaskListCount() {
      getExamineTaskListCount({
        orgIds: this.userFullOrgIds,
        status: 2,
        labelId: this.labelId_count || '',
        lliablepersons: this.userInfo.accountName,
        queryTimeType: 2,
        startTime: this.startTime,
        endTime: this.endTime,
      }).then((res) => {
        this.countData = res.data
      })
    },
    // 单位统计
    getExamineTaskOrgOrder() {
      getExamineTaskOrgOrder({
        orgIds: this.userFullOrgIds,
        status: 2,
        labelId: this.labelId_count || '',
        queryTimeType: 2,
        startTime: this.startTime,
        endTime: this.endTime,
      }).then((res) => {
        this.unitRankData = res.data
      })
    },
    // 人员统计
    getExamineTaskPeopleCount() {
      getExamineTaskPeopleCount({
        orgIds: this.userFullOrgIds,
        labelId: this.labelId_count || '',
        queryTimeType: 2,
        startTime: this.startTime,
        endTime: this.endTime,
      }).then((res) => {
        this.userData = res.data
      })
    },
    onSelectUser(item) {
      this.showUserSelect = false
      this.selectedUser = item
      this.account = item.accountName
      this.getTaskList()
    },
    handleOpenUserSelect() {
      this.showUserSelect = true
    },
    goUnitRank(params = {}) {
      this.$router.push({
        name: 'InspectUnitRank',
        params: {
          ...params,
          labelId: this.labelId_count,
          startTime: this.startTime,
          endTime: this.endTime,
        },
      })
    },
    goPersonalRank(params) {
      this.$router.push({
        name: 'InspectPersonalRank',
        params: {
          ...params,
          labelId: this.labelId_count,
          startTime: this.startTime,
          endTime: this.endTime,
        },
      })
    },
    onListLabelChange(v) {
      this.labelId_list = v.value
      this.getTaskList()
    },
    onPickerChange(key, v) {
      this[key] = v.value
      this.getTaskList()
    },
    formatter(day) {
      const _year = day.date.getFullYear()
      const _month = day.date.getMonth()
      const _date = day.date.getDate()
      if (_year == theYear && _month == theMonth && _date == theDay) {
        day.className = 'is-today'
      }
      if (
        uncompletedDays.indexOf(this.$moment(day.date).format('yyyy-MM-DD')) >
        -1
      ) {
        day.topInfo = '1'
      }
      if (
        completedDays.indexOf(this.$moment(day.date).format('yyyy-MM-DD')) > -1
      ) {
        day.bottomInfo = '1'
      }
      return day
    },
    handleCapsuleChange(key) {
      this.capsule = key
    },
    switchCalendar(step) {
      if (step === 1) {
        if (month < 11) {
          month = month + 1
        } else {
          year = year + 1
          month = 0
        }
      } else {
        if (month == 0) {
          year = year - 1
          month = 11
        } else {
          month = month - 1
        }
      }
      this.minDate = new Date(year, month, 1)
      this.maxDate = this.$moment(this.minDate).endOf('month').toDate()
      this.selectedDay = null
      this.showCalendar = false
      this.defaultDate = null
      completedDays = []
      uncompletedDays = []
      this.$nextTick(() => {
        this.showCalendar = true
      })
      this.getExamineTaskDailyStats()
      this.getTaskList()
    },
  },
}
</script>
<style lang='scss'>
@import '../../styles/variables.scss';
.inspect-statistic {
  padding-bottom: 60px;
  margin-top: 54px;
  .yt-capsule {
    position: relative;
    width: 174px;
    height: 34px;
    background: #ffffff;
    border: 1px solid $color-theme;
    border-radius: 34px;
    margin-left: 1px;
    &__item {
      position: relative;
      flex: 1;
      height: 34px;
      color: $color-theme;
      font-size: 16px;
      z-index: 1;
      transition: color 0.2s;
      &.is-active {
        color: #fff;
      }
    }
    &::before {
      content: '';
      position: absolute;
      top: 50%;
      width: 50%;
      height: 33px;
      border-radius: 33px;
      background: $color-theme;
      transition: left 0.2s;
      transform: translateY(-50%);
    }
    &.active1 {
      &::before {
        left: 0.5px;
      }
    }
    &.active2 {
      &::before {
        left: calc(50% - 1px);
      }
    }
  }
  &__calendar {
    position: relative;
    margin-top: 10px;
    .van-calendar__header {
      box-shadow: none;
    }
    .van-calendar__header-title {
      display: none;
    }
    .van-calendar__header-subtitle,
    .van-calendar__header-title,
    .van-calendar__month-title {
      font-weight: normal;
    }
    .van-calendar__body {
      overflow: hidden;
    }
    .van-calendar__month {
      display: none;
      &:first-child {
        display: block;
      }
    }
    .van-calendar__day {
      height: 50px;
      font-size: 14px;
      &.is-today {
        &::before {
          content: '';
          position: absolute;
          top: 50%;
          left: 50%;
          margin-top: -15px;
          margin-left: -15px;
          width: 30px;
          height: 30px;
          border-radius: 15px;
          background: rgba(105, 186, 113, 0.4);
        }
      }
    }
    .van-calendar__selected-day {
      width: 30px;
      height: 30px;
      border-radius: 15px;
      background: #69ba71;
      z-index: 1;
    }
    .cell-mark {
      position: absolute;
      bottom: 0;
      left: 50%;
      margin-left: -3px;
      display: inline-block;
      width: 6px;
      height: 6px;
      border-radius: 3px;
      &.is-success {
        background-color: #69ba71;
      }
      &.is-cross {
        background-color: #f8b80e;
      }
    }
    .van-calendar__bottom-info,
    .van-calendar__top-info {
      position: absolute;
      top: initial;
      bottom: 0;
      left: 50%;
      margin-left: -3px;
      display: inline-block;
      width: 6px;
      height: 6px;
      border-radius: 3px;
      color: transparent;
    }
    .van-calendar__bottom-info {
      background-color: #69ba71;
    }
    .van-calendar__top-info {
      background-color: #f8b80e;
    }
    .arrow {
      position: absolute;
      top: 0;
      padding: 15px;
      font-size: 14px;
      color: #999;
      opacity: 0.8;
    }
    .arrow-right {
      right: 0;
    }
    .arrow-left {
      left: 0;
    }
  }
  &__filter {
    margin-top: 10px;
  }
  &__list {
    margin-top: 10px;
  }
  .inspect-complete {
    margin-top: 20px;
  }
  .inspect-ranklist {
    margin-top: 20px;
  }
  .count-filter {
    margin-top: 10px;
  }
  .man-list {
    padding: 5px 10px 0;
    flex-wrap: wrap;
    .inspect-man {
      margin: 0 5px 10px 5px;
      width: calc(50vw - 20px);
    }
  }
  .inspectList_cell_top {
    margin-top: 0;
    margin-left: 0;
    margin-right: 0;
  }
  .inspectList_cell {
    box-shadow: 0px 2px 10px 2px rgba(181, 200, 206, 0.5);
    border-radius: 5px;
    margin-top: 10px;
    padding: 0;
  }
}
</style>